<template>
  <div class="content-container">
    
    <!-- 工具栏 -->
    <div ref="adminContentTools" class="content-tools-wrap hidden">
      	<div class="tools-left f-l">
      		
      		<el-button-group>
             <el-button type="primary" @click="handleAdd">新增设备</el-button>
			   </el-button-group>

      	</div>
      	<div class="tools-right f-r">
      		
			      <div class="search-wrap" style="display: inline-block;">
              <el-input placeholder="请输入关键词" v-model="query.keywords">
                <template slot="append">
                  <i class="icon el-icon-search"></i>
                </template>
              </el-input>
            </div>
			
      	</div>
    </div>
    <!-- 内容栏--表格 -->
    <div class="content-table-wrap" v-loading="loading" loading-type="chrome-circle-turn">

    	<el-table
        border
        v-if="data"
        size="small"
        :data="data"
        height="500px"
        :header-cell-style="{background:'#42b983',color:'#ffffff'}"
        :cell-style="{borderWidth:0}"
        style="width: 100%"
      >
    		
        <el-table-column
          fixed
          prop="id"
          label="ID"
          width="120">
        </el-table-column>

    		<el-table-column
		      prop="deviceNo"
		      label="设备编号"
		      width="150">
		    </el-table-column>

		    <el-table-column
		      prop="online"
		      label="在线状态"
		      width="80">
          <template slot-scope="scope">
            <div>
              <i v-if="getDeviceStatus(scope.row.deviceData)" class="icon iconfont ipc-line-status" style="color: #00cc66;font-weight: 700"></i>
              <i v-if="!getDeviceStatus(scope.row.deviceData)" class="icon iconfont ipc-line-status"></i>
            </div>
          </template>
		    </el-table-column>

		    <el-table-column
		      prop="name"
		      label="设备名称"
		      width="150">
		    </el-table-column>

        <el-table-column
          label="采集时间"
          width="150">
          <template slot-scope="scope">
            <div>
              <div v-if="scope.row.deviceData && scope.row.deviceData.createTime">
                {{scope.row.deviceData.createTime}}
              </div>
              <div v-if="!scope.row.deviceData || !scope.row.deviceData.createTime">
                暂无数据
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="data"
          label="数据"
          width="250">

          <template slot-scope="scope">
            <div>
              {{ getDeviceData(scope.row.deviceData) }}
            </div>
          </template>

        </el-table-column>

		    <el-table-column
          class="oprate"
		    	fixed="right"
		      label="操作"
          width="180"
		    >

		      <template slot-scope="scope">
            <i class="icon iconfont ipc-dash-borad" @click="$router.push({
              path: '/data/chart',
              query: {
                deviceNo: scope.row.deviceNo
              }
            })"></i>
            <i class="icon iconfont ipc-edit" @click="handleEdit(scope.row)"></i>
            <i class="icon iconfont ipc-search-online"></i>
            <i class="icon iconfont ipc-clear" @click="handleDel(scope.row)"></i>
		      	

		      </template>

		    </el-table-column>

    	</el-table> 

      <!-- 分页 -->
      <div ref="adminContentPagination" class="content-pagination-wrap">
        <el-pagination
            background
            :current-page="page.currentPage"
            :page-sizes="pageSizes"
            :page-size="page.pageSize"
            @current-change = "handlechange"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total">
        </el-pagination>
      </div> 
    </div>

    <!-- 修改dialog -->
    <edit-dialog
    	:visible="editDialogVisible"
    	:form.sync='editForm'
      :type="editType"
    	@cancel="editDialogCancel"
      @confirm="editDialogConfirm"
    ></edit-dialog>

  </div>

</template>

<script>
import { mapGetters } from 'vuex'

import {
  list,
  edit,
  del,
} from "@/api/equipment/equipment";

import editDialog from '@/components/agriculture/equipment/editDialog.vue'  
 

import adminMixins from "@/mixins/admin"
export default {
  name: 'role',
  mixins:[adminMixins],
  components:{
    editDialog
  },
  computed: {
    ...mapGetters([
      'name',
      'permission',
      'userInfo'
    ])
  },
  data(){
  	return{
      showMap: false,
      query:{
        keywords:''
      },
      //1新增，2修改
      editType:1,
      loading:true,
  		//修改模态框的显示隐藏
  		editDialogVisible:false,
  		data:null,
      testData:[
        {
          id:"334995096",
          number:"73F15233E6F3",
          online:'在线',
          name:"山东师范农场采集设备2",
          acquisitionTime:"2019-12-19 16:34:49",
          data:'18 ℃ | 36.4 %RH | 3767.9 ℃ | 16.3 %RH ',
        }
      ],
  		page: {
    	  pageSize: 10,
    	  currentPage: 1,
    	  total: 0
  	  },
  	  pageSizes:[10,20,30,40,50,100],
  	  editForm:{}
  	}
  },
  mounted(){
    //设置dom尺寸
    this.setSize();
  	this.loadData(this.page)
  },
  methods:{
    //新增分页效果
    handlechange(val){
      this.page.currentPage = val;
      this.loadData(this.page)
    },
  	//请求table数据
  	loadData(page, params = {}){
  		  this.loading = true;
      	list(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {

        	this.loading = false;
          const result = res.data.data.records;
          
          this.page.currentPage = res.data.data.current;
          this.page.total = res.data.data.total;
        	this.data = this.convertData(result);
          this.data.forEach(item => {
            item.location = item.location === '' ? {} : JSON.parse(item.location);
          })
          //this.data = this.testData;
      	});
      	
  	},
    convertData(data){

      return data;
    },

    //新增
    handleAdd(){
        this.editForm = {
          location: {
            address: '',
            p: '',
            Q: ''
          }
        };
        
        //模态框显示
        this.editDialogVisible = true;
    },
    //刷新当前页
    refresh(){
      this.loadData(this.page)
    },
  	//点击操作的编辑
  	handleEdit(row){
      console.log(row, '00000000')
  		this.editType = 2;
      this.editForm = row;
      //模态框显示
      this.editDialogVisible = true;
  	},
  	//点击操作的删除
  	handleDel(row){
  		console.log(row)

  		this.$confirm('此操作将永久删除该设备, 是否继续?', '提示', {
          	confirmButtonText: '确定',
          	cancelButtonText: '取消',
          	type: 'warning'
        }).then(()=>{
        	return del(row.id);
        }).then((res) => {

        	this.loadData(this.page)
          	this.$message({
            	type: 'success',
            	message: '删除成功!'
          	});
        }).catch(() => {
          	this.$message({
            	type: 'info',
            	message: '已取消删除'
          	});          
        });
  	},
  	//取消
  	editDialogCancel(){
      this.editDialogVisible = false;
  	},
    //确认
    editDialogConfirm(form){
      form.data.location.hasOwnProperty('p') && delete form.data.location.p;
      edit(form.data).then((res)=>{

        //this.editDialogVisible = false;
        this.loadData(this.page)
            this.$message({
              type: 'success', 
              message: this.editType === 1 ? '添加成功!' : '修改成功'
            });
        this.editDialogVisible = false;
      })
    },
    //获取设备在线状态
    getDeviceStatus(data){
      if(!data) return false;
      if(data.dtype == 1){
        if(data.status == 1){
          return true
        }else{
          return false
        }
      }
      if(data.dtype == 2){
        if(data.status1 == 1 || data.status2 == 1 || data.status3 == 1 || data.status4 == 1){
          return true;
        }else{
          return false
        }
      }

      return false
    },
    //获取设备数据
    getDeviceData(row){
      var arr = [];
      //空气湿度
      if(row.airHumidity){
        arr.push("空气湿度："+row.airHumidity)
      };
      //空气温度
      if(row.airTemperature){
        arr.push("空气温度："+row.airTemperature)
      };
      //土壤电导率
      if(row.soilConductivity){
        arr.push("土壤电导率："+row.soilConductivity)
      };
      //土壤湿度
      if(row.soilMoisture){
        arr.push("土壤湿度："+row.soilMoisture)
      };
      //土壤温度
      if(row.soilTemperature){
        arr.push("土壤温度："+row.soilTemperature)
      };
      //光照
      if(row.sunlight){
        arr.push("光照："+row.sunlight)
      }


      //继电器相关
      if(String(row.status1)){
        row.status1 == 1 ? arr.push("继电器1：开") : arr.push("继电器1：关")
      }

      if(String(row.status2)){
        row.status2 == 1 ? arr.push("继电器2：开") : arr.push("继电器2：关")
      }

      if(String(row.status3)){
        row.status3 == 1 ? arr.push("继电器3：开") : arr.push("继电器3：关")
      }

      if(String(row.status4)){
        row.status4 == 1 ? arr.push("继电器4：开") : arr.push("继电器4：关")
      }

      if(arr.length){
        return arr.join('|')
      }

      return '';
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  &-container {

  }
  /***搜索栏***/
  &-search-wrap{
    padding: 15px;
    border-bottom: 1px solid #E8EBEE;
  }
  /***工具栏***/
  &-tools-wrap{
    padding: 15px;
  }
  /***内容栏***/
  &-table-wrap{
    position: relative;
    padding: 15px;
    .cell{
      .icon{
        margin-right: 10px;
      }
    }
  }
  /***分页***/
  &-pagination-wrap{
    text-align: right;
  	padding-top: 15px;
  }
}
</style>